import {Component, ViewChild} from '@angular/core';
import {Config, NavController, NavParams, Platform} from 'ionic-angular';
import {Helper} from "../../common/Helper";
import {SubPage} from "../../common/subPage";
import {CONST} from "../../common/const";

@Component({
  selector: 'page-iframe',
  templateUrl: 'iframe.html',
})
export class IframePage extends SubPage {

  @ViewChild('iframe') iframe: any
  iframeElm: any
  url: any = ''
  title: string = ''

  constructor(public navCtrl: NavController,
              public navParams: NavParams,
              public platform: Platform,
              public config: Config,
              public helper: Helper) {
    super(config)
    this.registerBackButton()
    this.messageManage=this.messageManage.bind(this)
  }

  registerBackButton() {
    this.platform.registerBackButtonAction(() => {
      this.back()
    }, 1);
  }

  back() {
    this.sendMsg('goBack')
  }

  close() {
    this.helper.stopLoading()
    this.navCtrl.pop()
  }

  sendMsg(message) {
    if(this.iframeElm.contentWindow){
      this.iframeElm.contentWindow.postMessage(message, '*')
    }
  }

  messageManage(e){
    let data = e.data
    switch (data.code) {
      //加载成功
      case CONST.IFRAME_CODE_DID_LOAD:
        this.iframeDidLoad()
        break;
      case CONST.IFRAME_CODE_SET_TITLE:
        this.title = data.data
        break;
      case CONST.IFRAME_CODE_CLOSE:
        this.close()
        break;
    }
  }

  iframeDidLoad(){
  }

  ionViewDidLoad() {
    this.iframeElm = this.iframe.nativeElement
    window.addEventListener('message', this.messageManage)
  }

  ionViewDidEnter() {
    this.url = this.navParams.get('url')
    this.helper.loading('加载中..',true,false)
    this.iframeElm.onload = ()=>{
      this.helper.stopLoading()
    }
  }

  ionViewWillLeave() {
    Helper.eventManage.emit('app/setBackButtonAction')
    window.removeEventListener('message', this.messageManage)
  }

}
